import { Button, Checkbox, Flex, Form, Input, message } from 'antd'
import { apis } from '@/api'
import { useRouter } from '@/routes'
import { useUserStore } from '@/store'
import { SystemLoginForm } from '@/types'

/**
 * 登录页面
 */
const LoginPage = () => {
  const [form] = Form.useForm<SystemLoginForm>()
  const router = useRouter()
  const userStore = useUserStore()
  async function login() {
    const values = await form.validateFields()
    const res = await apis.systemLoginApi.login(values)
    if (res.success) {
      apis.localStorageApi.setItem(apis.LocalStorageKey.LOGIN, 1)
      userStore.setToken(String(new Date().getTime()))
      router.toHomePage()
    } else {
      message.error(res.msg)
    }
  }

  return (
    <Form
      form={form}
      layout="vertical"
      style={{ width: 400, margin: 'auto', marginTop: 100 }}
      onFinish={login}
    >
      <Form.Item name="username">
        <Input placeholder="请输入用户名" />
      </Form.Item>
      <Form.Item name="password">
        <Input.Password placeholder="请输入密码" />
      </Form.Item>
      <Flex justify="space-between" align="baseline">
        <Form.Item name="remember" valuePropName="checked">
          <Checkbox>记住我</Checkbox>
        </Form.Item>
        <Button type="link" size="middle">
          忘记密码
        </Button>
      </Flex>
      <Form.Item wrapperCol={{ span: 24 }}>
        <Button type="primary" style={{ width: '100%' }} onClick={login}>
          登录
        </Button>
      </Form.Item>
    </Form>
  )
}

export default LoginPage
